package hello.util;

import io.jsonwebtoken.*;
import org.apache.tomcat.util.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @Author: m01
 * @Date: created at  2018/12/20  15:22
 * @Modified By:
 */
public final  class JwtUtils {


    private final static Logger logger = LoggerFactory.getLogger(JwtUtils.class);

    private JwtUtils(){}


    public static final String getToken(Map<String,String> user, Long existsmills) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS384;

        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        Map<String, Object> headerMap = new HashMap<>();
        headerMap.put("type", "JWT");
        headerMap.put("alg", "ES256");//实际上会自动填充

        Map<String, Object> claims = new HashMap<>();
        claims.put("username", "m01");
        claims.put("role", "admin");
        JwtBuilder builder = Jwts.builder()
                .setHeader(headerMap)
                .setClaims(claims)
                .setIssuedAt(now)
                .setSubject("moly")
                .signWith(signatureAlgorithm, getSecretkey());

        long expMills = nowMillis;
        if (existsmills >= 0) {
            expMills += existsmills;
        } else {
            expMills += 1000 * 60 * 1;//默认有效一分钟
        }
        Date exp = new Date(expMills);
        builder.setExpiration(exp);
        return builder.compact();
    }


    private final static String sereckkey = "#%*sdaasasdf&3";

    private static final SecretKey getSecretkey() {
        byte[] encodedkey = Base64.decodeBase64(sereckkey);
        SecretKey key = new SecretKeySpec(encodedkey, 0, encodedkey.length, "AES");
        return key;
    }

    public final static Jws<Claims> parseJWT(String jwt) {
        Jws<Claims> jwt1 = null;
        if (jwt==null){
            return null;
        }
        try {
            jwt1 = Jwts.parser()
                    .setSigningKey(getSecretkey())
                    .parseClaimsJws(jwt);
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }

        return jwt1;
    }
}
